import {Component, OnInit} from '@angular/core';
import {AddSysUserComponent} from '../add-sys-user.component';
import {ErrRes} from '../../../../../frame/global/err-res';
import {SysUser} from '../../sys-user.type';
import {Services} from '../../../../../frame/module/services';
import {HttpRequestClient} from '../../../../../frame/http-request-client/http-request-client';
import {UrlRou} from '../../../../../frame';
import {SysOrganizeCondition} from "../../../sys-organize/sys-organize.type";
import {Md5} from "ts-md5/dist/md5";
import {SysRoleCondition} from "../../../sys-role/sys-role.type";

@Component({
    selector: 'app-main-add-sys-user',
    templateUrl: './main-add-sys-user.component.html',
    styleUrls: ['./main-add-sys-user.component.css']
})
export class MainAddSysUserComponent implements OnInit {

    errRes = new ErrRes();

    domain = new SysUser();

    extend = {
        domain: {
            default: () => {
                this.domain.serAudit = 'WAIT_SUBMIT';
                this.domain.serUsing = 'ENABLE';
            },
            serAudit: () => {
                return 'serAudit';
            },
        },
    };

    func = {
        save: {
            req: (event) => {
                let assign = Object.assign({}, this.domain);
                assign.serPass = assign.serPass && Md5.hashStr(assign.serPass).toString();
                Services.sysUser.save(assign, this.func.save.callback).subscribe();
            },
            callback: {
                success: (result) => {
                    HttpRequestClient.router.navigate([UrlRou.sysUser.list, {
                        moduleId: "system-management",
                        menuId: "sys-user"
                    }]);
                },
                error: (result) => {
                    this.errRes.error = result.error;
                    this.errRes.statusText = result.statusText;
                }
            }
        }
    };

    organizeDomains = [];
    roleDomains = [];
    initOrganizeAndRoleDomains = () => {
        const sysOrganize = new SysOrganizeCondition();
        Services.sysOrganize.list(sysOrganize, {
            page: 0,
            size: 200,
            orders: "createTime-desc,serNum-asc"
        }).subscribe(item => {
            this.organizeDomains = item.page.content;
        });

        const sysRole = new SysRoleCondition();
        Services.sysRole.list(sysRole, {
            page: 0,
            size: 200,
            orders: "createTime-desc,serNum-asc"
        }).subscribe(item => {
            this.roleDomains = item.page.content;
        });
    };

    constructor(public addSysUser: AddSysUserComponent) {
        this.addSysUser.main = this;
    }

    ngOnInit() {
        this.extend.domain.default();
        this.initOrganizeAndRoleDomains();
    }

}
